package com.sonicboom.nurun.resource;

import com.sonicboom.nurun.client.AxicomClient;
import com.sonicboom.nurun.client.DDMSClient;
import com.sonicboom.nurun.client.DDMSResult;
import com.sonicboom.nurun.client.WeChatClient;
import com.sonicboom.nurun.dao.IncentiveDAO;
import com.sonicboom.nurun.dao.LifeStyle;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.log4j.Logger;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Path("/incentive")
@Produces(MediaType.APPLICATION_JSON)
public class IncentiveResource {
    private static final Logger logger = Logger.getLogger(IncentiveResource.class);
    private final WeChatClient weChatClient;
    private final AxicomClient axicomClient;
    private final IncentiveDAO incentiveDAO;
    private final DDMSClient ddmsClient;

    public IncentiveResource(WeChatClient weChatClient, AxicomClient axicomClient, IncentiveDAO incentiveDAO) {
        this.weChatClient = weChatClient;
        this.axicomClient = axicomClient;
        this.incentiveDAO = incentiveDAO;

        ddmsClient = new DDMSClient();
    }

    @Path("/user/register")
    @POST
    public String register(String data) {
        logger.info("request:" + data);
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            JSONObject json = (JSONObject) JSONSerializer.toJSON(data);
            String userName = json.getString("user_name");
            String password = json.getString("password");
            String email = json.getString("email");

            if (incentiveDAO.getUser(userName) > 0) {
                result.put("code", "401");
                result.put("message", "账号已经存在");
            } else {
                DDMSResult registerResult = ddmsClient.register(userName, password, email);
                if (registerResult.getCode().equals("200")) {
                    long userId = incentiveDAO.addUser(userName, email);
                    result.put("code", "200");
                    result.put("message", "ok");
                    Map<String, String> userInfo = new HashMap<String, String>();
                    userInfo.put("user_id", String.valueOf(userId));
                    result.put("data", userInfo);
                } else {
                    result.put("code", registerResult.getCode());
                    result.put("message", registerResult.getMessage());
                }
            }
        } catch (Exception e) {
            logger.error("error when register user", e);
            result.put("code", "500");
            result.put("message", "账号注册失败");
        }

        return JSONSerializer.toJSON(result).toString(1);
    }

    @Path("/user/login")
    @POST
    public String login(String data) {

        logger.info("request:" + data);
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            JSONObject json = (JSONObject) JSONSerializer.toJSON(data);
            String userName = json.getString("user_name");
            String password = json.getString("password");

            DDMSResult loginResult = ddmsClient.login(userName, password);
            if (loginResult.getCode().equals("200")) {
                long userId = incentiveDAO.tryAddUser(userName);
                result.put("code", "200");
                result.put("message", "ok");
                Map<String, String> userInfo = new HashMap<String, String>();
                userInfo.put("user_id", String.valueOf(userId));
                result.put("data", userInfo);
            } else {
                result.put("code", loginResult.getCode());
                result.put("message", loginResult.getMessage());
            }
        } catch (Exception e) {
            logger.error("error when register user", e);
            result.put("code", "500");
            result.put("message", "登录失败");
        }

        return JSONSerializer.toJSON(result).toString(1);
    }

    @Path("/user/imlucky")
    @POST
    public String luckyDraw(@Context HttpServletRequest request, String data) {
        logger.info("request:" + data);
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Map<String, String> luckyDraw = new HashMap<String, String>();

            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("luckydrawsuccess")) {
                    result.put("code", "200");
                    result.put("message", "ok");
                    luckyDraw.put("win", String.valueOf(false));
                    result.put("data", luckyDraw);
                    return JSONSerializer.toJSON(result).toString(1);
                }
            }

            JSONObject json = (JSONObject) JSONSerializer.toJSON(data);
            String user_id = json.getString("user_id");
            LifeStyle lifeStyle = LifeStyle.parseFromCode(json.getString("life_style"));
            result.put("code", "200");
            result.put("message", "ok");
            long userId = Long.parseLong(user_id);
            if (incentiveDAO.isALuckyUserButAddressNotFill(userId)) {
                luckyDraw.put("win", String.valueOf(true));
                luckyDraw.put("token", incentiveDAO.getToken(userId));
                result.put("data", luckyDraw);
            } else {
                int alreadyGivenPrizeCount = incentiveDAO.getAlreadyGivenPrizeCount();
                int availablePrizeCount = incentiveDAO.getAvailablePrizeCount();

                if (availablePrizeCount - alreadyGivenPrizeCount > 0) {
                    String token = UUID.randomUUID().toString();
                    incentiveDAO.addLuckyDrawRecord(userId, lifeStyle, token);
                    luckyDraw.put("win", String.valueOf(true));
                    luckyDraw.put("token", token);
                    result.put("data", luckyDraw);
                } else {
                    luckyDraw.put("win", String.valueOf(false));
                    result.put("data", luckyDraw);
                }
            }
        } catch (Exception e) {
            result.put("code", "500");
            result.put("message", "抽奖失败，网络异常，可重试");
        }

        return JSONSerializer.toJSON(result).toString(1);
    }

    @Path("/user/address")
    @POST
    public String addAddress(String data) {
        logger.info("request:" + data);
        Map<String, String> result = new HashMap<String, String>();
        try {
            JSONObject json = (JSONObject) JSONSerializer.toJSON(data);
            String user_id = json.getString("user_id");
            String token = json.getString("token");
            String real_name = json.getString("real_name");
            String province = json.getString("province");
            String city = json.getString("city");
            String address = json.getString("address");
            String contact = json.getString("contact");

            if (incentiveDAO.isValidToken(token)) {
                incentiveDAO.addUserAddress(Long.parseLong(user_id), real_name, province, city, address, contact);
                result.put("code", "200");
                result.put("message", "ok");
            } else {
                result.put("code", "432");
                result.put("message", "token已失效");
            }
        } catch (Exception e) {
            result.put("code", "500");
            result.put("message", "信息提交失败，网络异常，可重试");
        }

        return JSONSerializer.toJSON(result).toString(1);
    }

    @Path("/wechat/share/config")
    @GET

    public String getJSShareConfig(@QueryParam("url") String url) {
        return weChatClient.getShareConfig(url);
    }


    @Path("/wechat/share/config")
    @POST
    public String getJSShareConfigWithPost(String request) {
        return weChatClient.getJSShareConfig(request);
    }


}
